import numpy as np

import urlearning.DimacsGraph as DimacsGraph

class TopPPopsConstraint:

    def __init__(self):
        pass

    def createConstrainedGraph(self, sc, p=1):
        # find the parents, according to the top-p POPS constraint
        constrainedGraph = DimacsGraph.DimacsGraph( len(sc), weighted=False, directed=True)

        for x in range(len(sc)):
                        
            if p > 0:
                # the parent sets are already sorted, so just take the top p
                topP = sc.parents[x][:p]
            else:
                topP = sc.parents[x]

            # set all of the present parents in the adjacency matrix
            for parents in topP:
                # check which variables are present in the parent set
                for y in range(len(sc)):
                    i = np.uint64(1 << y)
                    if parents & i > 0:
                        # disallow self-edges (not sure where they come from)
                        if x == y:
                            continue
                        constrainedGraph.addEdge(y, x)
                        #print("Child: {}, Parent: {}".format(x, y))

        return constrainedGraph

